
import express from 'express'
import path from 'path'
import cookieParser from 'cookie-parser'
import compress from 'compression'
import morgan from 'morgan'
import fs from 'fs'
import createError from 'http-errors'
const FileStreamRotator = require('file-stream-rotator');
const app = express()

const logDirectory = __dirname + '/log';
 
// ensure log directory exists 
fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory);
// create a rotating write stream 
var accessLogStream = FileStreamRotator.getStream({
  date_format: 'YYYY-MM-DD',
  filename: logDirectory + '/%DATE%.log',
  frequency: 'daily',
  verbose: false,
  max_logs : "30d"
});
 
// setup the logger
app.use(morgan('combined', { stream: accessLogStream ,format: "default"}))

app.use(morgan('dev'))
app.use(compress());
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.resolve(__dirname, './public')));

app.get('/', function (req, res) {
  res.send('hello, world!')
})

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.send('error');
});

module.exports = app